import { useChatStore } from '@/stores/chat';
import { useNoticeStore } from '@/stores/notice';
import { WsResponseMessageType, WsReqMsgContentType } from './wsType';

import { worker } from './initWorker';
import { MessageItem, NoticeItem, UserInfo } from '@/services/type';

class WS {
    #tasks: WsReqMsgContentType[] = [];
    // 重连🔐
    #connectReady = false;

    constructor() {
        this.initConnect()
        // 收到消息
        worker.addEventListener('message', this.onWorkerMsg)

        // 后台重试次数达到上限之后，tab 获取焦点再重试
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden && !this.#connectReady) {
                this.initConnect()
            }
        })
    }

    initConnect = () => {
        // 从 localStorage 读取用户信息
        const userInfo: any = localStorage.getItem("user");
        let uid = null;
        // 获取用户内码
        if (userInfo) {
            uid = (JSON.parse(userInfo) as UserInfo).yhnm;
        }
        // 初始化 ws
        worker.postMessage({ "type": "initWS", "value": (uid ? uid : null) });
    }

    onWorkerMsg = (e: MessageEvent<any>) => {
        const params: { type: string; value: unknown } = JSON.parse(e.data)
        switch (params.type) {
            case 'message': {
                this.onMessage(params.value as string)
                break;
            }
            case 'open': {
                this.#dealTasks()
                break;
            }
            case 'error': {
                this.#onClose()
                break;
            }
        }
    }

    // 重置一些属性
    #onClose = () => {
        this.#connectReady = false
    }

    #dealTasks = () => {
        this.#connectReady = true
    }

    #send(data: WsReqMsgContentType) {
        worker.postMessage({ "type": "message", "value": data });
    }

    send = (params: WsReqMsgContentType) => {
        if (this.#connectReady) {
            this.#send(params)
        } else {
            // 放到队列
            this.#tasks.push(params)
        }
    }

    // 收到消息回调
    onMessage = (value: string) => {
        // FIXME 可能需要 try catch,
        const params: { type: WsResponseMessageType; data: unknown } = JSON.parse(value);
        const chatStore = useChatStore();
        const noticeStore = useNoticeStore();
        switch (params.type) {
            // 收到消息
            case WsResponseMessageType.MESSAGE: {
                chatStore.pushMsg(params.data as MessageItem)
                break;
            }
            // 收到通知提醒信息
            case WsResponseMessageType.HANDLE_NOTICE_INFO: {
                noticeStore.pushNoticeInfo(params.data as NoticeItem);
                break;
            }
            default: {
                console.log('接收到未处理类型的消息:', params)
                break;
            }
        }
    }
}

export default new WS()